<template>
    <div style="width: 100%;">
        <!-- 搜索表单 -->
        <el-form :inline="true" ref="formRef" :model="formInline" class="demo-form-inline">
            <el-form-item label="工号">
                <el-input v-model="formInline.staffNo" placeholder="请输入工号" clearable />
            </el-form-item>
            <el-form-item label="姓名">
                <el-input v-model="formInline.name" placeholder="请输入姓名" clearable />
            </el-form-item>
            <el-form-item label="部门">
                <el-select v-model="formInline.department" placeholder="请选择部门" clearable>
                    <el-option v-for="department in departments.departmentList" :key="department.value"
                        :label="department.label" :value="department.label"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item class="search">
                <el-button type="primary" :icon="Refresh" @click="resetFormInline">重置</el-button>
                <el-button type="primary" :icon="Search" @click="searchData">查询</el-button>
            </el-form-item>
        </el-form>
        <!-- 按钮组 -->
        <div class="btn-group">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button type="danger" @click="handleDelete">删除</el-button>
        </div>
        <!-- 表格 -->
        <div class="table">
            <el-table :data="tableData" style="width: 100%" border height="420" show-overflow-tooltip
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40" label="全选" />
                <el-table-column fixed label="索引" type="index" :index="indexMethod" align="center" width="55" />
                <el-table-column prop="staff_no" label="工号" />
                <el-table-column prop="staff_name" label="姓名" />
                <!-- <el-table-column prop="sex" label="性别" /> -->
                <el-table-column prop="age" label="年龄" />
                <el-table-column prop="tel_no" label="联系电话" />
                <el-table-column prop="position" label="职位" />
                <el-table-column prop="department_name" label="部门" />
                <el-table-column fixed="right" label="操作" width="180">
                    <template #default="scope">
                        <el-button type="primary" @click="handleDetail(scope.row)">详情</el-button>
                        <el-button type="danger" @click="deleteEmployee(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
        <div class="pagination-wrapper">
            <el-pagination class="pagination" v-model:current-page="page.pageNum" v-model:page-size="page.pageSize"
                :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="page.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <!-- 弹窗-新增员工 -->
        <el-dialog class="dialog" v-model="dialogVisibleAdd" title="新增员工" width="800" @close="handleCloseAdd">
            <el-form class="dialog-add-form" :inline="true" :model="dialogFormAdd" :rules="dialogFormAddRules"
                ref="dialogAddFormRef">
                <el-form-item label-width="120px" prop="name" label="姓名">
                    <el-input v-model="dialogFormAdd.name" placeholder="请输入姓名" clearable />
                </el-form-item>
                <el-form-item label-width="120px" prop="age" label="年龄">
                    <el-input v-model="dialogFormAdd.age" placeholder="请输入年龄" clearable />
                </el-form-item>

                <el-form-item label-width="120px" prop="telNo" label="联系电话">
                    <el-input v-model="dialogFormAdd.telNo" placeholder="请输入联系电话" clearable />
                </el-form-item>

                <el-form-item label-width="120px" prop="sex" label="性别">
                    <el-select v-model="dialogFormAdd.sex" placeholder="请选择性别" clearable>
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label-width="120px" prop="departmentName" label="部门">
                    <el-select v-model="dialogFormAdd.departmentName" placeholder="请选择部门" @change="departmentNameChange"
                        clearable>
                        <el-option v-for="department in departments.departmentList" :key="department.value"
                            :label="department.label" :value="department.label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label-width="120px" prop="position" label="职位">
                    <el-select v-model="dialogFormAdd.position" placeholder="请选择职位" clearable>
                        <el-option v-for="position in departments.positionList" :key="position.value"
                            :label="position.label" :value="position.label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label-width="120px" prop="basePay" label="基本工资">
                    <el-input type="number" v-model="dialogFormAdd.basePay" placeholder="请输入基本工资" clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCloseAdd">取消</el-button>
                    <el-button type="primary" @click="handleAddEmployee">
                        添加
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 弹窗-员工详情 -->
        <el-dialog class="dialog" v-model="dialogVisible" title="员工详情" width="800" :close="handleClose">
            <el-form class="dialog-form" :inline="true" :model="dialogForm" ref="dialogFormRef">
                <el-form-item label-width="120px" label="工号">
                    <el-input v-model="dialogForm.staffNo" placeholder="工号" disabled clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="姓名">
                    <el-input v-model="dialogForm.name" placeholder="姓名" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="性别">
                    <el-input v-model="dialogForm.sex" placeholder="性别" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="年龄">
                    <el-input v-model="dialogForm.age" placeholder="年龄" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="联系电话">
                    <el-input v-model="dialogForm.telNo" placeholder="联系电话" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="职位">
                    <el-input v-model="dialogForm.position" placeholder="职位" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="部门">
                    <el-input v-model="dialogForm.departmentName" placeholder="部门" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="基本工资">
                    <el-input v-model="dialogForm.basePay" placeholder="基本工资" clearable />
                </el-form-item>
                <el-form-item label-width="120px" label="头像">
                    <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="upFile">
                        <img v-if="dialogForm.avatar" :src="dialogForm.avatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <!-- <el-input v-model="dialogForm.avatar" placeholder="头像" clearable /> -->
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose">关闭</el-button>
                    <el-button type="primary" @click="update">
                        修改
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { fileUpload, ossUrl } from '@/utils/ali-oss.js'
import { Plus } from '@element-plus/icons-vue'
import { queryEmployees, updateEmployee, delEmployee, addEmployee } from "@/api/employee"
import { queryDepartments } from '@/api/department'

// 分页
const page = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0,
})

// 表单-搜索-ref
const formRef = ref(null)

// 表单-搜索-数据
const formInline = reactive({
    staffNo: '',
    name: '',
    department: '',
})

// 表格数据
const tableData = ref([])

// 详情-弹窗
const dialogVisible = ref(false)
const dialogFormRef = ref(null)
const dialogForm = reactive({})

// 新增-弹窗
const dialogVisibleAdd = ref(false)
const dialogAddFormRef = ref(null)
const dialogFormAddRules = {
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    age: [
        { required: true, message: '请输入年龄', trigger: 'blur' },
        { min: 1, max: 120, message: '年龄范围在 1 到 120 之间', trigger: 'blur' },
    ],
    telNo: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                const regex = /^1[3-9]\d{9}$/;
                if (!regex.test(value)) {
                    callback(new Error('请输入正确的手机号码'));
                } else {
                    callback();
                }
            }, trigger: 'blur'
        }
    ],
    sex: [
        { required: true, message: '请选择性别', trigger: 'blur' }
    ],
    position: [
        { required: true, message: '请选择职位', trigger: 'blur' }
    ],
    departmentName: [
        { required: true, message: '请选择部门', trigger: 'blur' }
    ],
    basePay: [
        { required: true, message: '请输入基本工资', trigger: 'blur' },
        { min: 0, message: '基本工资不能为负数', trigger: 'blur' },
    ]
};
const dialogFormAdd = reactive({})

// 多选-id
const ids = ref([]);

// 表格索引
const indexMethod = (index) => {
    return page.pageSize * (page.pageNum - 1) + index + 1
}

// 部门和职位
const departments = reactive({
    departmentList: [],
    positionListAll: [],
    positionList: []
})

// 获取部门和职位
const getDepartments = async () => {
    try {
        const res = await queryDepartments();
        if (res.code === 0) {
            const departmentSet = new Set(departments.departmentList.map(d => d.label));
            res.data.list.forEach(item => {
                if (!departmentSet.has(item.department_name)) {
                    departments.departmentList.push({
                        value: item.department_name,
                        label: item.department_name
                    });
                    departmentSet.add(item.department_name);
                }
                departments.positionListAll.push({
                    value: item.department_name,
                    label: item.position
                });
            });
        } else {
            ElMessage.error(res.msg);
        }
    } catch {
        console.log("请求失败");
    }
}

const departmentNameChange = () => {
    departments.positionList = departments.positionListAll.filter(item => item.value == dialogFormAdd.departmentName)
}

// 重置
const resetFormInline = () => {
    formInline.department = '';
    formInline.staffNo = '';
    formInline.name = '';
    searchData();
}

// 搜索
const searchData = async () => {
    const data = {
        staffNo: formInline.staffNo,
        staffName: formInline.name,
        departmentName: formInline.department,
        pageNum: page.pageNum,
        pageSize: page.pageSize,
    }
    try {
        const res = await queryEmployees(data);
        if (res.code === 0) {
            tableData.value = res.data.list;
            page.total = res.data.total;
        } else {
            // ElMessage.error(res.msg);
        }
    } catch {
        console.log("请求失败");
    }
}

// 新增员工
const handleAddEmployee = () => {
    if (dialogAddFormRef.value) {
        dialogAddFormRef.value.validate(async (valid) => {
            if (!valid) return;
            const data = {
                staffName: dialogFormAdd.name,
                age: dialogFormAdd.age,
                telNo: dialogFormAdd.telNo,
                sex: dialogFormAdd.sex,
                position: dialogFormAdd.position,
                departmentName: dialogFormAdd.departmentName,
                basePay: dialogFormAdd.basePay
            }
            try {
                const res = await addEmployee(data);
                if (res.code === 0) {
                    ElMessage.success('新增成功！');
                    dialogVisibleAdd.value = false;
                    searchData();
                } else {
                    ElMessage.error('新增失败！');
                }
            } catch {
                console.log("请求失败");
            }
        })
    }
}

// 修改
const update = () => {
    if (dialogFormRef.value) {
        dialogFormRef.value.validate(async (valid) => {
            if (!valid) return;
            const data = {
                id: dialogForm.id,
                staffName: dialogForm.name,
                age: dialogForm.age,
                telNo: dialogForm.telNo,
                sex: dialogForm.sex,
                position: dialogForm.position,
                departmentName: dialogForm.departmentName,
                basePay: dialogForm.basePay,
                avator: dialogForm.avatar
            }
            try {
                const res = await updateEmployee(data);
                if (res.code === 0) {
                    ElMessage.success('修改成功！');
                    dialogVisible.value = false;
                    searchData();
                } else {
                    ElMessage.error('修改失败！');
                }
            } catch {
                console.log("请求失败");
            }
        })
    }
}

// 表格多选
const handleSelectionChange = (val) => {
    ids.value = val.map(item => item.id);
}

// 删除
const deleteEmployee = (ids) => {
    const data = Array.isArray(ids) ? ids : [ids];
    ElMessageBox.confirm('确认删除选中项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await delEmployee(data);
            if (res.code === 0) {
                ElMessage.success('删除成功！');
                searchData();
            } else {
                ElMessage.error('删除失败！');
            }
        } catch {
            console.log("请求失败");
        }
    }).catch(() => {
        console.log('取消删除');
    })
}

// 多选删除
const handleDelete = () => {
    if (ids.value.length === 0) {
        ElMessage.warning('请选择要删除的员工！');
        return
    }
    deleteEmployee(ids.value)
}

// 上传头像
const upFile = async (rawFile) => {
    const imgType = ["image/png", "image/jpg", "image/jpeg", "image/gif", "image/svg"]
    if (!imgType.includes(rawFile.file.type)) {
        ElMessage.warning('头像格式只能为图片！');
        return
    }
    const fileName = 'avator/' + dayjs().valueOf() + '_' + rawFile.file.name;
    const res = await fileUpload(fileName, rawFile.file);
    if (res.res.status == 200) {
        dialogForm.avatar = res.url;
        ElMessage.success('头像上传成功！');
    } else {
        ElMessage.error('头像上传失败！');
    }
}

// 详情-弹窗-打开
const handleDetail = (row) => {
    dialogVisible.value = true;
    dialogForm.id = row.id;
    dialogForm.staffNo = row.staff_no;
    dialogForm.name = row.staff_name;
    dialogForm.sex = row.sex;
    dialogForm.age = row.age;
    dialogForm.telNo = row.tel_no;
    dialogForm.position = row.position;
    dialogForm.departmentName = row.department_name;
    dialogForm.avatar = row.avator;
    dialogForm.basePay = row.base_pay;
}

// 详情-弹窗-关闭
const handleClose = () => {
    dialogVisible.value = false
    if (dialogFormRef.value) dialogFormRef.value.resetFields();
}

// 新增-弹窗-打开
const handleAdd = () => {
    dialogVisibleAdd.value = true;
}

// 新增-弹窗-关闭
const handleCloseAdd = () => {
    dialogVisibleAdd.value = false;
    if (dialogAddFormRef.value) dialogAddFormRef.value.resetFields();
}

// 分页
const handleSizeChange = (val) => {
    page.pageSize = val
    searchData()
}

const handleCurrentChange = (val) => {
    page.pageNum = val
    searchData()
}

onMounted(() => {
    searchData();
    getDepartments();
})


</script>

<style lang="scss" scoped>
.demo-form-inline {
    padding: 10px 20px 0;
}

.demo-form-inline .el-input {
    --el-input-width: 150px;
}

.demo-form-inline .el-select {
    --el-select-width: 150px;
}

.btn-group {
    box-sizing: border-box;
    padding-right: 20px;
    margin-bottom: 5px;
    margin-top: -15px;
    float: right;
}

.table {
    box-sizing: border-box;
    padding: 0 20px 0 15px;
}

.footer {
    position: relative;
    width: 100%;
    height: auto;
}

.pagination-wrapper {
    width: 100%;
    height: 44px;
    display: flex;
    justify-content: flex-end;
}

.pagination {
    margin-top: 15px;
    margin-right: 20px;
}

:deep(.el-dialog__body) {
    display: flex;
    justify-content: center;
}

.dialog-form {
    .el-input {
        --el-input-width: 220px;
    }
}

.avatar-uploader .el-upload {
    border: 1px dashed #8c939d;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: none;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.dialog-add-form {
    .el-input {
        --el-input-width: 220px;
    }

    .el-select {
        --el-select-width: 220px;
    }
}
</style>